var leadTable;
$(document).ready(function() {
	leadTable = $('#leadTable').dataTable({
		"sDom": 'flrtip',
		"bFilter" : true,
		"bStateSave" : false,
		"aaSorting" : [ [ 1, "asc" ] ],	
		"sPaginationType" : "bootstrap",
		"oLanguage" : {
			"sLengthMenu" : "Display _MENU_ records per page",
			"sZeroRecords" : "Nothing found - sorry",
			"sInfo" : "Showing _START_ to _END_ of _TOTAL_ records",
			"sInfoEmpty" : "Showing 0 to 0 of 0 records"
		},
		"bProcessing" : true,
		"bServerSide" : true,
		"sAjaxSource" : "leadsList",
		"aoColumns" : [ 
		                {"mData" : "checkbox" },
		                {"mData" : "id" },
		                {"mData" : "name"},
		                {"mData" : "leadstatus"}, 
		                {"mData" : "company"},
		                {"mData" : "owner"}
		               ],
		"aoColumnDefs": [
		                 { "sName": "checkbox",   "aTargets": [ 0 ] },
		                 { "sName": "id",   "aTargets": [ 1 ] },
		                 { "sName": "name",  "aTargets": [ 2 ] },
		                 { "sName": "leadstatus", "aTargets": [ 3 ] },
		                 { "sName": "company",  "aTargets": [ 4 ] },
		                 { "sName": "owner",    "aTargets": [ 5 ] },
		                 { "sClass" : "hide",   "aTargets" : [ 1 ]}
		               ],
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
				  			$('td:eq(2)', nRow).html('<a href="viewLead?id=' + aData.id + '">' +aData.name + '</a>');
				                   return nRow;
		}
	});
	    
	initCrudButtons();
	
	

});

/**
 * Initializing crud buttons 
 */
function initCrudButtons(){
	
	$("#bt_update").click(function() {
		var searchIDs = $("#leadTable input:checkbox:checked").map(function(){
		      return $(this).val();
		    }).get(); // <----
		    console.log(searchIDs);
			if(searchIDs.length==1){				 
				window.location = "editLead?id=" + searchIDs[0];
			}
			else{
				selectError();
			}
	});
	
	$("#bt_appointment").click(function() {
		var searchIDs = $("#leadTable input:checkbox:checked").map(function(){
		      return $(this).val();
		    }).get(); // <----
		    console.log(searchIDs);
			if(searchIDs.length==1){				 
				window.location = "newAppointment?id=" + searchIDs[0];
			}
			else{
				selectError();
			}
	});
	
	$("#bt_call").click(function() {
		var searchIDs = $("#leadTable input:checkbox:checked").map(function(){
		      return $(this).val();
		    }).get(); // <----
		    console.log(searchIDs);
			if(searchIDs.length==1){				 
				window.location = "newCall?id=" + searchIDs[0];
			}
			else{
				selectError();
			}
	});
	
	$("#bt_delete").click(function() {
		var searchIDs = $("#leadTable input:checkbox:checked").map(function(){
		      return $(this).val();
		    }).get(); // <----
		    console.log(searchIDs);
			if(searchIDs.length>0){				 
				 $('#deleteModalLabel').html('Warning:');
		    	  $('#deleteModalMsg').html('Are you sure you want to delete this Lead ?');
		    	  $('#deleteModelBody').attr('class', 'modal-body alert alert-danger');
		    	  $('#deleteModel').modal();
		    	  $( "#btnDelete" ).click(function() {
		    		  deleteLead(searchIDs);
		    		});
			}
			else{
				error();
			}
	});
	
	$("#bt_transfer").click(function() {
		var searchIDs = $("#leadTable input:checkbox:checked").map(function(){
		      return $(this).val();
		    }).get(); // <----
		    console.log(searchIDs);
			if(searchIDs.length>0){
				 $(".modal-body #leadId").val(searchIDs);
				 $("#bt_transfer").attr("href", "#transferModel");
			}
			else{
				error();
			}
	});
	
	$("#bt_share").click(function() {
		var searchIDs = $("#leadTable input:checkbox:checked").map(function(){
		      return $(this).val();
		    }).get(); // <----
		    console.log(searchIDs);
			if(searchIDs.length>0){
				 $(".modal-body #leadId").val(searchIDs);
				 $("#bt_share").attr("href", "#shareModel");
			}
			else{
				error();
			}
	});
	
	$("#bt_test").click(function() {
		
		$("#bt_test").attr("href", "#myModal1");
		
	//	leadTable.fnClearTable(0);
//		var newUrl = "leadSearch";
//		leadTable.fnReloadAjax(newUrl);
		//leadTable.fnDraw();    
	});
}

/**
 * Delete button handler
 * @param type
 * @param id
 */
function deleteLead(id){
	$.ajax({
        type: "POST",
        url: 'deleteLead?id='+id,
        success: function(response,status,xhr){
        	leadTable.$('tr.row_selected').remove();
            	$("#leadTable").dataTable().fnDraw();
        },
	    error: function (xhr, ajaxOptions, thrownError) {
	  	  $('#errorModalLabel').html("Error Server "+xhr.status+":");
	  	  $('#errorModalMsg').html(xhr.responseText);
	  	  $('#errorModelBody').attr('class', 'modal-body error alert-error');
	  	  $('#errorModal').modal();
	    }
   });
}